import { type AxiosResponse } from 'axios';
import api from '@/store/api';

export const useGlobalStore = defineStore('global', () => {
  const HOST_STATE = {
    on: 'xyz.openbmc_project.State.Host.HostState.Running',
    off: 'xyz.openbmc_project.State.Host.HostState.Off',
    error: 'xyz.openbmc_project.State.Host.HostState.Quiesced',
    diagnosticMode: 'xyz.openbmc_project.State.Host.HostState.DiagnosticMode',
  };

  const serverStateMapper = (hostState: any) => {
    switch (hostState) {
      case HOST_STATE.on:
      case 'On': // Redfish PowerState
        return 'on';
      case HOST_STATE.off:
      case 'Off': // Redfish PowerState
        return 'off';
      case HOST_STATE.error:
      case 'Quiesced': // Redfish Status
        return 'error';
      case HOST_STATE.diagnosticMode:
      case 'InTest': // Redfish Status
        return 'diagnosticMode';
      default:
        return 'unreachable';
    }
  };

  const assetTag = ref(null as string | null);
  const bmcTime = ref(null as Date | null);
  const modelType = ref(null as string | null);
  const serialNumber = ref(null as string | null);
  const serverStatus = ref('unreachable');
  const languagePreference = ref(
    localStorage.getItem('storedLanguage') || 'en-US',
  );
  const isUtcDisplay = ref(
    localStorage.getItem('storedUtcDisplay')
      ? JSON.parse(localStorage.getItem('storedUtcDisplay') as string)
      : true,
  );
  const username = ref(localStorage.getItem('storedUsername'));
  const isAuthorized = ref(true);
  const userPrivilege = ref(null as string | null);

  const setAssetTag = (value: string) => (assetTag.value = value);
  const setModelType = (value: string) => (modelType.value = value);
  const setSerialNumber = (value: string) => (serialNumber.value = value);
  const setBmcTime = (value: Date) => (bmcTime.value = value);
  const setServerStatus = (value: string) =>
    (serverStatus.value = serverStateMapper(value));
  const setLanguagePreference = (value: string) =>
    (languagePreference.value = value);
  const setUsername = (value: string) => (username.value = value);
  const setUtcTime = (value: string) => (isUtcDisplay.value = value);
  const setUnauthorized = () => {
    isAuthorized.value = false;
    window.setTimeout(() => {
      isAuthorized.value = true;
    }, 100);
  };
  const getBmcTime = async function () {
    return await api
      .get('/redfish/v1/Managers/bmc')
      .then((response: any) => {
        const bmcDateTime = response.data.DateTime;
        const date = new Date(bmcDateTime);
        setBmcTime(date);
      })
      .catch((error: any) => console.log(error));
  };

  const getSystemInfo = function () {
    api
      .get('/redfish/v1/Systems/system')
      .then(
        (
          {
            data: {
              AssetTag,
              Model,
              PowerState,
              SerialNumber,
              Status: { State } = {} as { State: any },
            },
          } = {} as AxiosResponse<any>,
        ) => {
          setAssetTag(AssetTag);
          setSerialNumber(SerialNumber);
          setModelType(Model);
          if (State === 'Quiesced' || State === 'InTest') {
            // OpenBMC's host state interface is mapped to 2 Redfish
            // properties "Status""State" and "PowerState". Look first
            // at State for certain cases.
            setServerStatus(State);
          } else {
            setServerStatus(PowerState);
          }
        },
      )
      .catch((error: any) => console.log(error));
  };

  const getNowDateTime = function () {
    const date = new Date();
    let year: string | number = date.getFullYear();
    let month: string | number = date.getMonth() + 1;
    let day: string | number = date.getDate();
    let hour: string | number = date.getHours();
    let minutes: string | number = date.getMinutes();
    let seconds: string | number = date.getSeconds();
    year = '' + year;
    if (month >= 1 && month <= 9) {
      month = '0' + month;
    }
    if (day >= 0 && day <= 9) {
      day = '0' + day;
    }
    if (hour >= 0 && hour <= 9) {
      hour = '0' + hour;
    }
    if (minutes >= 0 && minutes <= 9) {
      minutes = '0' + minutes;
    }
    if (seconds >= 0 && seconds <= 9) {
      seconds = '0' + seconds;
    }
    return year + month + day + hour + minutes + seconds;
  };

  const formatDateTime = function (date: Date) {
    const y = date.getFullYear();
    let m: number | string = date.getMonth() + 1;
    m = m < 10 ? '0' + m : m;
    let d: number | string = date.getDate();
    d = d < 10 ? '0' + d : d;
    let h: string | number = date.getHours();
    h = h < 10 ? '0' + h : h;
    let minute: number | string = date.getMinutes();
    minute = minute < 10 ? '0' + minute : minute;
    let second: number | string = date.getSeconds();
    second = second < 10 ? '0' + second : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
  };

  const formatDate = function (date: Date) {
    const y = date.getFullYear();
    let m: number | string = date.getMonth() + 1;
    m = m < 10 ? '0' + m : m;
    let d: number | string = date.getDate();
    d = d < 10 ? '0' + d : d;
    return y + '-' + m + '-' + d;
  };

  function transformString(input: string) {
    let result = input.replace(/-(\w)/g, (match, char) => {
      return char.toUpperCase();
    });

    if (result.length > 0) {
      result = result.charAt(0).toUpperCase() + result.slice(1);
    }

    return result;
  }

  return {
    assetTag,
    bmcTime,
    modelType,
    serialNumber,
    serverStatus,
    languagePreference,
    isUtcDisplay,
    username,
    isAuthorized,
    userPrivilege,
    setAssetTag,
    setModelType,
    setSerialNumber,
    setBmcTime,
    setServerStatus,
    setLanguagePreference,
    setUsername,
    setUtcTime,
    setUnauthorized,
    getBmcTime,
    getSystemInfo,
    getNowDateTime,
    formatDateTime,
    formatDate,
    transformString,
  };
});
